//
// Created by Administrator on 2025/1/13.
//

#include "FindCodec.h"

bool *print_codec_info(const struct AVCodec *codec) {
    const char *type = av_get_media_type_string(codec->type);
    enum AVCodecID av_codec_id = codec->id;
    LOGD("Codec ID: %d\n", av_codec_id);
    LOGD("Codec Name: %s\n", codec->name);
    LOGD("Codec Type: %s\n", type ? type : "unknown");
    LOGD("Capabilities: 0x%x\n", codec->capabilities);
    LOGD("\n");
    const AVCodec *h264_encoder = avcodec_find_encoder(av_codec_id);
    // boolean isEncoderOrDecoder[2] ={};
    bool isEncoderOrDecoder[] ={false, false};
    if (h264_encoder) {
        isEncoderOrDecoder[0] = true;
    }else {
        isEncoderOrDecoder[0] = false;
    }
    const AVCodec *h264_decoder = avcodec_find_decoder(av_codec_id);
    if (h264_decoder) {
        isEncoderOrDecoder[1] = true;
    }else {
        isEncoderOrDecoder[1] = false;
    }
    // 分配内存以返回数组
    bool *result = (bool *)malloc(2 * sizeof(bool));
    if (result == NULL) {
        return NULL;  // 内存分配失败
    }
    result[0] = isEncoderOrDecoder[0];
    result[1] = isEncoderOrDecoder[1];
    return result;
}
// AVMEDIA_TYPE_VIDEO, 视频
// AVMEDIA_TYPE_AUDIO,  音频
// AVMEDIA_TYPE_SUBTITLE, 字幕

// av_codec_id, AV_CODEC_ID_H264 视频的ID通常是AV_CODEC_ID_H264 音频的ID：AV_CODEC_ID_AAC
const AVCodec *getCodec(enum AVMediaType av_media_type,enum AVCodecID av_codec_id
                        ,  bool isEncoder, bool isDecorder) {
    // av_register_all();
    // avcodec_register_all();
    void *iter = NULL;
    const AVCodec *codec;
    // av_codec_iterate 遍历所有codec
    while ((codec = av_codec_iterate(&iter))) {
        if (codec->type == av_media_type) {
            bool *codec_info = print_codec_info(codec);
            if ((isEncoder == codec_info[0])&&(isDecorder == codec_info[1])) {
                free(codec_info);
                if (av_codec_id== codec->id) {
                    return codec;
                }
            }
        }
    }
    return NULL;
}
int initCodec() {
    void *iter = NULL;
    const AVCodec *codec;
    // av_codec_iterate 遍历所有codec
    while ((codec = av_codec_iterate(&iter))) {
            bool *codec_info = print_codec_info(codec);
            free(codec_info);
    }
    return 0;
}


